#include "FindTextDialog.h"
#include "ui_FindTextDialog1.h"
#include "ui_FindTextDialog2.h"

FindTextDialog::FindTextDialog(QWidget *parent, QPlainTextEdit *plainText) : QDialog(parent), plainText_(plainText)
{
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, "Xairy", "TextVoiceReader");
    int theme = settings.value("theme").toInt();

    switch (theme) {
    case 1: {
        auto ui2 = new Ui::FindTextDialog2;
        ui2->setupUi(this);
        ui = new Ui::FindTextDialog1;
        *ui = *(reinterpret_cast<Ui::FindTextDialog1*>(ui2));
        delete ui2;
        break;
    }
    case 0: //如果是0就默认为2
    case 2: {
        ui = new Ui::FindTextDialog1;
        ui->setupUi(this);
        break;
    }
    }

    auto flags = this->windowFlags();
    this->setWindowFlags(flags & ~Qt::WindowContextHelpButtonHint);

    QTextCursor cursor = plainText_->textCursor();
    ui->edtFind->setText(cursor.selectedText());
}

FindTextDialog::~FindTextDialog()
{
    delete ui;
}

void FindTextDialog::on_btnReplace_clicked()
{
    QTextCursor cursor = this->plainText_->textCursor();
    cursor.removeSelectedText();
    cursor.insertText(ui->edtReplace->text());
    this->plainText_->setTextCursor(cursor);
}

void FindTextDialog::on_btnReplaceAll_clicked()
{
    QTextCursor cursor = plainText_->textCursor();
    int index = cursor.position();
    QString content = plainText_->toPlainText();
    content.replace(ui->edtFind->text(), ui->edtReplace->text());
    plainText_->setPlainText(content);
    cursor = plainText_->textCursor();
    cursor.setPosition(index);
    plainText_->setTextCursor(cursor);
}

void FindTextDialog::on_btnFind_clicked()
{
    plainText_->find(ui->edtFind->text());
}
